#include <iostream>
#include <nlohmann/json.hpp>
#include "Broadcast.h"
#include "MessageQueue.h"
#include "config.h"
#include "MySQLClient.h"
#include <mysql_driver.h>
#include <mysql_connection.h>

#include <libwebsockets.h>
#include "WebSocketServer.h"

using namespace std;

const char *loginstatus[] = { "success" , "username" , "password"};

Broadcast *broadcaster ;

static void loginReceipt(int ret )
{
    nlohmann::json j;
    // 设置 id 和动态的 status 值
    j["id"] = 1002;
    j["status"] = loginstatus[ret];

    string json_str = j.dump();
    // 输出 JSON
    std::cout << json_str << std::endl;  // 格式化输出
    broadcaster->send( json_str, "255.255.255.255");
}

int main() 
{
#if 1
    MessageQueue mq_create(SOCKETMASSAGE,true);
    broadcaster = new Broadcast(45454); // 使用端口 12345
    WebSocketServer server(8081);
    server.start();
    

    MySQLClient dbClient("localhost", "leader", "123456", "ChatTools");
    if (!dbClient.connect())
    {
        std::cerr << "Failed to connect to the database after multiple attempts\n";
        return 1;
    }

    broadcaster->send("Hello, Broadcast!", "255.255.255.255");
    // 模拟一些运行时间
    while (1)
    {
        //broadcaster->send("Hello, Broadcast!", "255.255.255.255");
        string json_str = mq_create.receiveMessage();
        if( json_str.length() !=  0 )
        {
            auto json = nlohmann::json::parse(json_str, nullptr, false);
            if (json.is_discarded()) {
                std::cerr << "Failed to parse JSON." << std::endl;
                continue;
            }
            int id = json["id"];
            cout<<"id:"<<id<<endl;
            switch (id)
            {
            case 1001:
            {
                // 访问 JSON 对象的内容
                std::string pass = json["login"]["pass"];
                std::string status = json["login"]["status"];
                std::string user = json["login"]["user"];
                loginReceipt( dbClient.loginSelectQuery(user,pass) );
                break;
            }
            case 1003:
            {
                //注册用户
            }
            default:
                break;
            }
        }
        usleep(500*1000);
    }
#endif
    return 0;
}
